<template>
	<main-content hasTab>
		<view class="bg-con" v-if="listData">
			<view class="query-box bg-white">
				<view class="query-box-view">
					<view class="m-b-8">
						<u-tabs :list="DATE_TPYE_A" inactive-color='rgba(153, 153, 153, 1)' :active-color='maiColor'
							:is-scroll="false" v-model="tabVal" @change="changeTab"></u-tabs>
					</view>
					<view class="p-x-16 p-b-16">
						<view
							class="m-b-8 p-r-12 p-l-6 flex flex-row justify-between items-center report-datetime-picker-box">
							<view class="">
								<uni-datetime-picker type="date" :border="false" return-type='date'
									v-model="queryForm.rTime" @change='onChange' :clearIcon='false' />
							</view>
							<view class="report-datetime-picker-tip font-13">
								统计截止 {{parseTime(TimeUtils.create().subtract(1, 'days')._date,'{y}-{m}-{d}')}}
							</view>
						</view>
						<view class="btn-box flex flex-row justify-between datetime-btn">
							<view class="w-50 p-r-4">
								<u-button size="mini" :hair-line="false"
									@click="getDate(false)">前一{{DATE_TPYE_A[tabVal].name[0]}}</u-button>
							</view>
							<view class="w-50 p-l-4">
								<u-button size="mini" :hair-line="false"
									@click="getDate(true)">后一{{DATE_TPYE_A[tabVal].name[0]}}</u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="flex flex-col p-16"> <!-- style="height: 100vh;" -->
				<view class="report-item-box p-16">
					<view class="flex flex-row justify-between">
						<group-title>
							<template #icon>
								<view class="main-color">
									<u-icon name="title-icon" custom-prefix="custom-icon" />
								</view>
							</template>
							商户数
						</group-title>
					</view>
					<view class="flex flex-row flex-wrap justify-between">
						<view class="w-50 flex p-y-8 flex-col justify-content items-center"
							v-for="(item,index) in mchConfig" :key='item.field'>
							<view class="main-color font-18 font-medium p-b-4">
								{{listData[item?.field]}}{{item.unit}}
							</view>
							<view class="list-title font-12">
								{{item.subTitle}}
								<u-icon name="question-circle-fill" @tap="showTipFn(item.tip)"
									v-if='!$System.isEmpty(item.tip)' style="color:#D8D8D8 ;" />
							</view>
						</view>
					</view>
				</view>
				<view class="report-item-box p-16 m-t-16">
					<view class="flex flex-row justify-between">
						<group-title>
							<template #icon>
								<view class="main-color">
									<u-icon name="title-icon" custom-prefix="custom-icon" />
								</view>
							</template>
							商户交易流水</group-title>
					</view>
					<view class="flex flex-row flex-wrap justify-between">
						<view class="w-100 p-y-8" v-show="tabVal!=2">
							<qiun-data-charts canvas2d="true" :type="tabVal==0?'column':'line'" :opts="opts"
								:chartData="chartData" :ontouSch='true' />
						</view>
						<view class="w-100 p-y-8" v-show="tabVal==2">
							<qiun-data-charts canvas2d="true" type="line" :opts="opts" :chartData="chartData"
								:ontouch='true' />
						</view>
					</view>
				</view>
				<view class="report-item-box p-16 m-t-16">
					<view class="flex flex-row justify-between">
						<group-title>
							<template #icon>
								<view class="main-color">
									<u-icon name="title-icon" custom-prefix="custom-icon" />
								</view>
							</template>
							代理商数</group-title>
					</view>
					<view class="flex flex-row flex-wrap justify-between">
						<view class="w-50 flex p-y-8 flex-col justify-content items-center"
							v-for="(item,index) in agentConfig" :key='item.field'>
							<view class="main-color font-18 font-medium p-b-4">
								{{listData[item?.field]}}{{item.unit}}
							</view>
							<view class="list-title font-12">
								{{item.subTitle}}
								<u-icon name="question-circle-fill" @tap="showTipFn(item.tip)"
									v-if='!$System.isEmpty(item.tip)' />
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-popup v-model="showTip" mode="center" width="500rpx" border-radius="14" :closeable='true'>
			<view>
				<view class="p-14">
					<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						提示</group-title>

				</view>
				<view class="p-16">
					{{tipContent}}
				</view>
				<view class="p-16">
					<u-button type="primary" @click="showTip=false">确认</u-button>
				</view>
			</view>
		</u-popup>
	</main-content>
</template>
<script setup name='index'>
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow,
		onReady
	} from '@dcloudio/uni-app'
	import {
		useCommonStore
	} from '@/stores/common.js'
	import {
		useUserStore
	} from '@/stores/user.js'
	import {
		debounce,
		selectDictLabel,
		formatToMoney,
		parseTime
	} from '@/common/common.js'
	import {
		TimeUtils
	} from '@/common/myDay.js'
	import {
		reportApi
	} from '@/common/api/report/index.js'
	const commonStore = useCommonStore()
	const {
		proxy
	} = getCurrentInstance()

	const api = {
		getData: (data = {}) => {
			let mydata = {
				...data
			}
			return reportApi.getDate(mydata)
		},
	}

	const DATE_TPYE_A = [{
		name: '日报',
		value: 'days',
	}, {
		name: '周报',
		value: 'weeks',
	}, {
		name: '月报',
		value: 'months',
	}]

	const maiColor = computed(() => {
		return proxy.$System.maiColor.value
	})

	const initForm = {
		rTime: TimeUtils.getCurrentTime(), //TimeUtils.getDayStart().valueOf(), TimeUtils.getDayEnd().valueOf()
		rTimeBegin: TimeUtils.getDayStart(TimeUtils.getCurrentTime()).valueOf(),
		rTimeEnd: TimeUtils.getDayEnd(TimeUtils.getCurrentTime()).valueOf(),
		dateStatus: 'days', //状态，0正常使用，1禁止开代理商，2禁止开商户，3禁止操作人员登录，4系统停止使用，5停止全部收款，6全部禁用
		pageNo: 1,
		pageSize: 10,
	}
	const queryForm = ref({
		...initForm
	})
	const tabVal = ref(0)
	const changeTab = (val) => {
		tabVal.value = val
		queryForm.value.dateStatus = DATE_TPYE_A[val].value
		onChange(queryForm.value.rTime)
	}
	const onSearch = (value) => {
		getList()
	}

	const onChange = (val) => {
		console.log('val===>', val);
		if (!val) {
			queryForm.value.rTimeBegin = undefined
			queryForm.value.rTimeEnd = undefined
		} else {
			if (queryForm.value.dateStatus == 'days') {
				queryForm.value.rTimeBegin = TimeUtils.getDayStart(val).valueOf()
				queryForm.value.rTimeEnd = TimeUtils.getDayEnd(val).valueOf()
			} else if (queryForm.value.dateStatus == 'weeks') {
				queryForm.value.rTimeBegin = TimeUtils.getWeekRangeByDate(val).start.valueOf()
				queryForm.value.rTimeEnd = TimeUtils.getWeekRangeByDate(val).end.valueOf()
			} else if (queryForm.value.dateStatus == 'months') {
				queryForm.value.rTimeBegin = TimeUtils.getMonthRangeByDate(val).start.valueOf()
				queryForm.value.rTimeEnd = TimeUtils.getMonthRangeByDate(val).end.valueOf()
			}
		}
		// console.log('开始时间', parseTime(queryForm.value.rTimeBegin));
		// console.log('结束时间', parseTime(queryForm.value.rTimeEnd));
		onSearch()
	}
	const getDate = (val) => {
		// months/weeks/days
		let unit = queryForm.value.dateStatus || 'days'
		if (val) {
			queryForm.value.rTime = TimeUtils.create(queryForm.value.rTime).add(1, unit)._date
		} else {
			queryForm.value.rTime = TimeUtils.create(queryForm.value.rTime).subtract(1, unit)
				._date
		}
		onChange(queryForm.value.rTime)
	}

	const chartsMap = {
		tradeAmt: '交易金额',
		refundAmt: '退款金额',
		revenueAmt: '营收金额',
		paidUpAmt: '实收金额',
	}
	const listData = ref()
	const getList = async (pageNo, pageSize, ) => {
		// 统一显示加载框
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let res = await api.getData(queryForm.value)
		listData.value = res.data
		handleChartData(listData.value.tradeMerchantList)
		// 隐藏加载框
		uni.hideLoading()
	}

	// 重置查询条件
	function resetQuery() {
		queryForm.value = {
			...initForm
		}
	}

	const handleChartData = (list) => {
		if (!list) return
		chartData.value.categories = []
		chartData.value.series = [{
			name: "当日数据",
			data: [35, 36, 31, 33, 13, 34]
		}]
		if (queryForm.value.dateStatus == 'days') {
			let dayData = {}
			chartData.value.series[0].data = []
			for (let key in list[0]) {
				dayData = list[0][key]
			}
			chartData.value.series[0].name = "当日数据"
			Object.keys(chartsMap).forEach(item => {
				chartData.value.categories.push(chartsMap[item])
				chartData.value.series[0].data.push((dayData[item] / 100).toFixed(2))
			})
		} else {
			let categories = []
			let dataMap = {}
			list.forEach((item, i) => {
				dataMap[Object.keys(item)[0]] = item[Object.keys(item)[0]]
			})
			categories = Object.keys(dataMap).map(e => parseTime(e, '{m}-{d}')) /* '{y}-{m}-{d}' */
			chartData.value.categories = categories
			let dataarr = Object.keys(chartsMap).map(e => {
				return {
					name: chartsMap[e],
					data: Object.keys(dataMap).map(item => (dataMap[item][e] / 100).toFixed(2))
				}
			})
			chartData.value.series = dataarr
		}
	}

	// 图表
	const chartData = ref({
		categories: ["2018", "2019", "2020", "2021", "2022", "2023"],
		series: [{
			name: "当日数据",
			data: [35, 36, 31, 33, 13, 34]
		}]
	})
	const opts = computed(() => {
		let opt = {
			color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
				"#ea7ccc"
			],
			padding: [15, 10, 0, 15],
			enableScroll: false,
			dataLabel: false,
			legend: {},
			xAxis: {
				disableGrid: true,
				scrollShow: true,
				itemCount: 4,
				rotateLabel: false, //倾斜
			},
			yAxis: {
				gridType: "dash",
				dashLength: 2,
			},
			extra: {
				line: {
					type: "straight",
					width: 2,
					activeType: "hollow"
				}
			}
		}
		if (queryForm.value.dateStatus == 'months') {
			opt.xAxis.format = 'xAxisDemo3'
		} else {
			opt.xAxis.format = undefined
		}
		return opt
	})
	// 图表

	// 商户数配置
	const mchConfig = [{
		field: 'newMerchantNum',
		subTitle: '新增商户',
		unit: '户',
		tip: '进件成功的商户，进件通过时间＝归属日期'
	}, {
		field: 'activeMerchantNum',
		subTitle: '活跃商户',
		unit: '户',
		tip: '最近7天日均交易金额≥10元，时间判断：（截至归属月末判断活跃商户数）'
	}, {
		field: 'tradeMerchantNum',
		subTitle: '交易商户',
		unit: '户',
		tip: '支付成功的交易笔数大于等于1笔的商户，时间判断：（按每月有交易一笔的商户数）'
	}, {
		field: 'lossMerchantNum',
		subTitle: '流失商户',
		unit: '户',
		tip: '最近7天日均交易为0。时间判断：（截至归属月末判断流失商户数）'
	}]

	// 代理商数配置
	const agentConfig = [{
		field: 'newAgentNum',
		subTitle: '新增代理商',
		unit: '户',
	}, {
		field: 'agentNewAddMerchantNum',
		subTitle: '代理商新增商户',
		unit: '户',
		// }, {
		// 	field: 'tradeMerchantNum',
		// 	subTitle: '代理商总数',
		// 	unit: '户',
		// }, {
		// 	field: 'lossMerchantNum',
		// 	subTitle: '代理商商户总数',
		// 	unit: '户',
	}]

	const showTip = ref(false)
	const tipContent = ref('')
	const showTipFn = (val = '') => {
		showTip.value = true
		tipContent.value = val
	}

	onLoad(async (options) => {})
	onReady(() => {
		getList()
	})
</script>
<style lang='scss' scoped>
	.query-box {}

	.btn-box {
		:deep(.u-size-mini) {
			width: 100%;
		}
	}

	.report-datetime-picker-box {
		border-radius: 16rpx;
		background: rgba(243, 244, 246, 1);

		:deep(.uni-date-x) {
			background-color: rgba(243, 244, 246, 1);
		}

		.report-datetime-picker-tip {
			color: rgba(192, 196, 204, 1);
		}

	}

	.datetime-btn {

		:deep(.u-btn--default) {
			font-size: 28rpx;
			border-color: rgba(44, 93, 235, 0.1) !important;
			background-color: rgba(44, 93, 235, 0.1) !important;
			padding: 2rpx 0;
		}
	}

	.report-item-box {
		background-color: #fff;
		border-radius: 16rpx;
	}

	:deep(.u-card .u-card__head) {
		padding: 15px 15px 0 15px !important;
	}

	:deep(.u-card .u-card__foot) {
		padding: 0 15px 15px 15px !important;
	}
</style>
<style>
	page {
		background-color: rgba(246, 247, 248, 1);
	}
</style>